{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 如何计算多类支撑向量机损失的导数函数?\n",
    "\n",
    "$$\n",
    "\\begin{align*} L_i&=\\sum_{j\\neq y_i}\\max\\left(0, s_{i j}-s_{y_i}+1\\right)\\\\ s_{i j}&=w_j^T x_i+b_j\\end{align*}\n",
    "$$\n",
    "\n",
    "$$\n",
    "L_i=\\sum_{j\\neq y_i}\\max\\left(0, w_j^T x_i+b_j-\\left(w_{y_i}^T x_i+b_{y_i}\\right)+1\\right)\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 一、确定损失函数的组成部分\n",
    "\n",
    "对于每个类别 $j$，损失函数的一部分是 $\\max(0, s_{ij} - s_{y_i} + 1)$。这个表达式只有在 $s_{ij} - s_{y_i} + 1 > 0$ 时才不为零，即当类别 $j$ 的得分超过真实类别 $y_i$ 的得分时。\n",
    "\n",
    "### 二、计算梯度\n",
    "\n",
    "#### （一）对 $w_j$ 的梯度\n",
    "\n",
    "1. 当 $s_{ij} - s_{y_i} + 1 > 0$，$\\frac{\\partial}{\\partial w_j} (s_{ij} - s_{y_i} + 1)=\\frac{\\partial}{\\partial w_j} (w_j^T x_i + b_j - w_{y_i}^T x_i - b_{y_i} + 1)$。\n",
    "2. 这简化为 $x_i$ 的方向，因为 $\\frac{\\partial}{\\partial w_j} w_j^T x_i = x_i$ 且其他项关于 $w_j$ 的导数为 0。\n",
    "3. 因此，$\\frac{\\partial L_i}{\\partial w_j} = \\mathbf{1}(s_{ij} > s_{y_i} - 1) x_i$，其中 $\\mathbf{1}$ 是指示函数，当条件满足时为 1，否则为 0。\n",
    "\n",
    "#### （二）对 $b_j$ 的梯度\n",
    "\n",
    "类似地，$\\frac{\\partial}{\\partial b_j} (s_{ij} - s_{y_i} + 1)=\\mathbf{1}(s_{ij} > s_{y_i} - 1)$。\n",
    "\n",
    "### 三、汇总梯度\n",
    "\n",
    "在实际应用中，我们需要对所有样本 $i$ 和所有类别 $j$ 的梯度进行求和，以更新权重和偏置。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
